import { useEffect, useRef, useState } from 'react'
import { Group, Layer, Rect, Stage, Transformer } from 'react-konva'

export default function View() {
  const [selectedShape, setSelectedShape] = useState(null)
  const stageRef = useRef(null)
  const groupRef = useRef(null)
  const rectRef = useRef(null)
  const transformerRef = useRef(null)

  const [groupAttrs, setGroupAttrs] = useState({
    x: 500,
    y: 500,
    scaleX: 1,
    scaleY: 1,
    skewX: 0,
    skewY: 0,
    rotation: 0
  })

  useEffect(() => {
    console.log('🚀 ~ View ~ groupAttrs:', groupAttrs)
  }, [groupAttrs])

  const handleStageClick = e => {
    // 如果点击的是空白区域，取消选中
    if (e.target === e.target.getStage()) {
      setSelectedShape(null)
      return
    }

    // 如果点击的是矩形，选中它
    if (e.target.nodeType === 'Shape') {
      setSelectedShape(groupRef.current)
    }
  }

  return (
    <Stage width={window.innerWidth} height={window.innerHeight} ref={stageRef} onClick={handleStageClick}>
      <Layer>
        <Group
          ref={groupRef}
          draggable
          onDragEnd={e => {
            // 获取当前的变换状态
            const node = e.target
            const { x, y } = node.attrs

            // 更新 Rect 的位置
            const newX = groupAttrs.x + x
            const newY = groupAttrs.y + y

            // 重置 Group 位置并更新状态
            node.position({ x: 0, y: 0 })
            setGroupAttrs(prev => ({
              ...prev,
              x: newX,
              y: newY
            }))
          }}
          onTransformEnd={e => {
            // 获取当前的变换状态
            const node = e.target
            const { scaleX, scaleY, rotation, skewX, skewY } = node.attrs

            // 获取变换后的矩形位置
            const rect = rectRef.current
            const absPos = rect.getAbsolutePosition()

            // 计算新的属性
            const newAttrs = {
              x: absPos.x,
              y: absPos.y,
              scaleX: groupAttrs.scaleX * scaleX,
              scaleY: groupAttrs.scaleY * scaleY,
              rotation: groupAttrs.rotation + rotation,
              skewX: groupAttrs.skewX + skewX,
              skewY: groupAttrs.skewY + skewY
            }

            // 重置 Group 的变换并更新状态
            node.position({ x: 0, y: 0 }).scale({ x: 1, y: 1 }).skew({ x: 0, y: 0 }).rotation(0)

            setGroupAttrs(newAttrs)
          }}
        >
          <Rect
            ref={rectRef}
            x={groupAttrs.x}
            y={groupAttrs.y}
            scaleX={groupAttrs.scaleX}
            scaleY={groupAttrs.scaleY}
            rotation={groupAttrs.rotation}
            skewX={groupAttrs.skewX}
            skewY={groupAttrs.skewY}
            width={200}
            height={200}
            fill='yellow'
          />
        </Group>

        {selectedShape && (
          <Transformer
            ref={transformerRef}
            boundBoxFunc={(oldBox, newBox) => {
              // 限制最小尺寸
              if (newBox.width < 5 || newBox.height < 5) {
                return oldBox
              }
              return newBox
            }}
            nodes={[selectedShape]}
          />
        )}
      </Layer>
    </Stage>
  )
}
